package org.brakepedal.server.support.bluetooth;

import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import javax.bluetooth.ServiceRecord;
import javax.bluetooth.UUID;
import java.io.IOException;

/**
 * Date: 2024/4/1 13:50
 *
 * @author Huanyu Mark
 */
@Component
public class BtDeviceProvider implements MultiArgsObjectProvider<BtService> {

    private final ApplicationContext ctx;

    private final String btServiceBeanName;

    public BtDeviceProvider(ApplicationContext ctx) {
        this.ctx = ctx;
        btServiceBeanName = ctx.getBeanNamesForType(BtService.class)[0];
    }

    @Override
    public @NotNull BtService getObject(Object... args) throws BeansException {
        if(args.length < 1) {
            throw new BeanCreationException("BtDeviceProvider.getObject() args is null");
        }
        if(!(args[0] instanceof ServiceRecord record)) {
            throw new BeanCreationException("BtDeviceProvider.getObject() args[0] is not ServiceRecord");
        }
        if(args.length < 2 || !(args[1] instanceof UUID uuid)) {
            throw new BeanCreationException("BtDeviceProvider.getObject() args[1] is not UUID");
        }
        try {
            BtService service = new BtService(ctx,record,uuid);
            ctx.getAutowireCapableBeanFactory().configureBean(service,btServiceBeanName);
            return service;
        } catch (IOException e) {
            throw new BeanCreationException("BtDevice Creation Fail",e);
        }
    }
}
